import { FormProps } from "@/components/modal/form.modal"
import { Field_FormSave } from "@/components/utils/field.list"
import adminMenuService from "@/services/admin.menu.service"
import React, { useCallback } from "react"

import adminRulesService from "@/services/admin.rules.service"
import { FormRender } from "@whzhuke/antd"
import { arrayCommon } from "@whzhuke/common"

import { useFetch } from "@whzhuke/usehook"
import useForm from "antd/es/form/hooks/useForm"
import { MenuType, RulesType } from "@whzhuke/interface"

interface Props {
  rid: number
}
export const RulesMenu: React.FC<Props & FormProps> = props => {
  const { rid, onDone } = props
  const [form] = useForm()
  const onFinish = useCallback(
    value => {
      adminRulesService.itemConfigSet({ rid, rulesType: RulesType.菜单, data: value.data }).then(() => {
        useFetch.clear(adminRulesService.itemConfigList, [{ rid, rulesType: RulesType.菜单 }])
        onDone?.()
      })
    },
    [rid]
  )
  const [{ data: menuList }] = useFetch(adminMenuService.list, [{ pageSize: 9999, pageNum: 0, type: MenuType.SYS }])
  const [{ data: itemConfigList }] = useFetch(adminRulesService.itemConfigList, [{ rid, rulesType: RulesType.菜单 }])
  const treeData = arrayCommon.doTree(
    menuList.rows.map(m => ({ ...m, key: m.id })),
    "id",
    "parentId"
  )
  return (
    <FormRender
      form={form}
      initialValues={{ rid, data: itemConfigList.rows.map(m => m.data.list) }}
      layout="horizontal"
      onFinish={onFinish}
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      style={{ width: 600 }}
      fieldList={[
        {
          fieldType: "input",
          formItemConfig: {
            label: "rid",
            name: "rid",
            hidden: true
          }
        },
        {
          fieldType: "tree",
          formItemConfig: { required: !0, name: "data" },
          config: {
            checkable: !0,
            defaultExpandAll: !0,
            selectable: !1,
            treeData
          }
        },

        { ...Field_FormSave, formItemConfig: { wrapperCol: { offset: 8, span: 16 } } }
      ]}
      autoComplete="off"
    />
  )
}
